﻿using System;
using System.Collections.Generic;
using System.IO;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using YArchitech.Controls;
using YArchitech.Revit;
using HYElectricSetting;

namespace ElectricDim
{
	[Transaction(TransactionMode.Manual)]
	public class CmdLightningDim : IExternalCommand
	{
		public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
		{
			UIDocument activeUIDocument = commandData.Application.ActiveUIDocument;
			Document document = activeUIDocument.Document;
			LightningWireFilter lightningWireFilter = new LightningWireFilter();
			IList<Reference> list = null;
			try
			{
				list = activeUIDocument.Selection.PickObjects((Autodesk.Revit.UI.Selection.ObjectType)1, lightningWireFilter, "请选择防雷线（详图线）");
				if (list == null)
				{
					return Autodesk.Revit.UI.Result.Failed;
				}
			}
			catch
			{
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			FamilySymbol familySymbol = this.LoadFamilyClamp(document);
			if (familySymbol == null)
			{
				return Autodesk.Revit.UI.Result.Cancelled;
			}
			foreach (Reference reference in list)
			{
				DetailCurve detailCurve = document.GetElement(reference) as DetailCurve;
				this.DeleteClamp(detailCurve, document);
			}
			foreach (Reference reference2 in list)
			{
				DetailCurve detailCurve2 = document.GetElement(reference2) as DetailCurve;
				if (!detailCurve2.GeometryCurve.IsCyclic || detailCurve2.GeometryCurve.IsBound)
				{
					if (detailCurve2 is DetailLine)
					{
						DetailLine detailLine = detailCurve2 as DetailLine;
						this.LayoutClamp(detailLine, document, familySymbol);
					}
					else
					{
						DetailArc detailArc = detailCurve2 as DetailArc;
						this.LayoutClamp(detailArc, document, familySymbol);
					}
				}
			}
			return Autodesk.Revit.UI.Result.Succeeded;
		}

		private void DeleteClamp(DetailCurve detailCurve, Autodesk.Revit.DB.Document doc)
		{
			Curve geometryCurve = detailCurve.GeometryCurve;
			double z = geometryCurve.GetEndPoint(0).Z;
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc, doc.ActiveView.Id);
			filteredElementCollector.OfClass(typeof(FamilyInstance));
			if (filteredElementCollector != null)
			{
				Transaction transaction = new Transaction(doc, "DeleteClamp");
				transaction.Start();
				try
				{
					foreach (Element element in filteredElementCollector.ToElements())
					{
						FamilyInstance familyInstance = element as FamilyInstance;
						Family family = familyInstance.Symbol.Family;
						XYZ point = (familyInstance.Location as LocationPoint).Point;
						XYZ xyz = new XYZ(point.X, point.Y, z);
						if (family.Name.CompareTo("防雷线-支撑卡") == 0 && geometryCurve.Distance(xyz) <= 0.001)
						{
							doc.Delete(element.Id);
						}
					}
					transaction.Commit();
				}
				catch
				{
					transaction.RollBack();
				}
			}
		}

		private FamilySymbol LoadFamilyClamp(Autodesk.Revit.DB.Document doc)
		{
			FilteredElementCollector filteredElementCollector = new FilteredElementCollector(doc);
			filteredElementCollector.OfClass(typeof(Family));
			if (filteredElementCollector != null)
			{
				foreach (Element element in filteredElementCollector.ToElements())
				{
					Family family = element as Family;
					if (family.Name.CompareTo("防雷线-支撑卡") == 0)
					{
						foreach (FamilySymbol familySymbol in family.GetSymbols())
						{
							if (familySymbol.Name == "0")
							{
								return familySymbol;
							}
						}
					}
				}
			}
			FamilySymbol result = null;
			FileInfo fileInfo = null;
			Family family2 = ElectricMark.LightningMark(doc)[0].Load(doc, ref fileInfo);
			Transaction transaction = new Transaction(doc, "LoadFamily");
			transaction.Start();
			try
			{
				if (family2 == null)
				{
					return result;
				}
				foreach (FamilySymbol familySymbol2 in family2.GetSymbols())
				{
					if (familySymbol2.Name == "0")
					{
						result = familySymbol2;
						break;
					}
				}
				transaction.Commit();
			}
			catch
			{
				YJKMessageBox.Show("加载支撑卡族失败!");
				transaction.RollBack();
			}
			return result;
		}

		private void LayoutClamp(DetailLine detailLine, Autodesk.Revit.DB.Document doc, FamilySymbol fsClamp)
		{
			Curve geometryCurve = detailLine.GeometryCurve;
			double length = geometryCurve.Length;
			Transaction transaction = new Transaction(doc, "NewClamp");
			transaction.Start();
			try
			{
				int num = Convert.ToInt32(Math.Floor(length / this.m_dGap));
				double num2 = (length - (double)(num - 1) * this.m_dGap) * 0.5;
				XYZ endPoint = geometryCurve.GetEndPoint(0);
				XYZ xyz = (geometryCurve.GetEndPoint(1) - endPoint).Normalize();
				double num3 = XYZ.BasisX.AngleOnPlaneTo(xyz, XYZ.BasisZ);
				for (int i = 0; i < num; i++)
				{
					XYZ xyz2 = endPoint + xyz * (num2 + this.m_dGap * (double)i);
					UnifiedModified.ActivateFamilySymbol(fsClamp);
					FamilyInstance familyInstance = doc.Create.NewFamilyInstance(xyz2, fsClamp, doc.ActiveView);
					Line line = Line.CreateBound(xyz2, xyz2 + XYZ.BasisZ);
					ElementTransformUtils.RotateElement(doc, familyInstance.Id, line, num3);
				}
				transaction.Commit();
			}
			catch
			{
				transaction.RollBack();
			}
		}

		private void LayoutClamp(DetailArc detailArc, Autodesk.Revit.DB.Document doc, FamilySymbol fsClamp)
		{
			Curve geometryCurve = detailArc.GeometryCurve;
			double length = geometryCurve.Length;
			Transaction transaction = new Transaction(doc, "NewClamp");
			transaction.Start();
			try
			{
				int num = Convert.ToInt32(Math.Floor(length / this.m_dGap));
				double num2 = (length - (double)(num - 1) * this.m_dGap) * 0.5;
				Arc arc = geometryCurve as Arc;
				XYZ endPoint = geometryCurve.GetEndPoint(0);
				XYZ center = arc.Center;
				double radius = arc.Radius;
				double num3 = num2 / radius;
				double num4 = this.m_dGap / radius;
				XYZ normal = arc.Normal;
				for (int i = 0; i < num; i++)
				{
					XYZ xyz = Transform.CreateRotationAtPoint(normal, num3 + num4 * (double)i, center).OfPoint(endPoint);
					UnifiedModified.ActivateFamilySymbol(fsClamp);
					FamilyInstance familyInstance = doc.Create.NewFamilyInstance(xyz, fsClamp, doc.ActiveView);
					double num5 = Math.PI*.5 - (xyz - center).AngleOnPlaneTo(XYZ.BasisX, XYZ.BasisZ);
					Line line = Line.CreateBound(xyz, xyz + XYZ.BasisZ);
					ElementTransformUtils.RotateElement(doc, familyInstance.Id, line, num5);
				}
				transaction.Commit();
			}
			catch
			{
				transaction.RollBack();
			}
		}

		private double m_dGap = (double)ElectricSettingDataAssist.GetLightningSupportCardSpacing(1000) / 304.8;
	}
}
